package com.gykj.admin.config;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * Created by rohto.li on 2017/11/03.
 */
public class ShiroCacheManager implements CacheManager {

	private static final Logger logger = LoggerFactory.getLogger(ShiroCacheManager.class);

	private static volatile ShiroCacheManager redisCacheManager;

	@Autowired(required = false)
	private static RedisTemplate<String, Object> redisTemplate;

	private ShiroCacheManager() {
	};

	/**
	 * 单例模式，双重检查
	 * 
	 * @return
	 */
	public static ShiroCacheManager getInstance() {
		if (null == redisCacheManager) {
			synchronized (ShiroCacheManager.class) {
				if (null == redisCacheManager) {
					redisCacheManager = new ShiroCacheManager();
				}
			}
		}
		return redisCacheManager;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <K, V> Cache<K, V> getCache(String name) throws CacheException {
		logger.warn("get RedisCacheManager");
		return new ShiroCache<K, V>(name, (RedisTemplate<K, V>) redisTemplate);
	}

    public static void setRedisTemplate(RedisTemplate<String, Object> template) {
        redisTemplate = template;
    }
}
